selectDate=[];//日历控件的时间表
$(function(){
    loginName=baseFunction.getUrlParameterValueByKey("loginName");
    id=baseFunction.getUrlParameterValueByKey("id"); //当前选中信用卡的id
    aisle=baseFunction.getUrlParameterValueByKey("aisle"); //通道编号
    accountBalance=baseFunction.getUrlParameterValueByKey("accountBalance"); //账户余额
    addRate=baseFunction.getUrlParameterValueByKey("addRate"); //额外增加费率
    rmentMode=baseFunction.getUrlParameterValueByKey("rmentMode"); 
    ruleCode=baseFunction.getUrlParameterValueByKey("ruleCode"); 
    mainDate="";//账单日 还款日
    cardno="";//当前还款的银行卡号
    // 日历初始化
    var date2 = new Date();
    year = date2.getFullYear();  //当前年
    month = date2.getMonth() + 1; //当前月
    currentDate = date2.getDate(); //当前日
    

    getList(); //初始化
    // 各种提示
    $(".box .li .tip1").on("click",function(){
        $(".prompt").html("账单金额是您要制定还款计划的信用卡账单金额。").show(0).delay(2000).hide(0);
    })
    $(".box .li .tip2").on("click",function(){
        $(".prompt").html("卡片应预留额度比率是用于计算您卡片内应保留金额。").show(0).delay(2000).hide(0);
    })
    $(".box .li .tip3").on("click",function(){
        $(".prompt").html("预留金额是您卡片事先预留的可消费额度，用途是还款计划先消费后还款的操作使用。请确保卡片应预留额度，避免还款计划有误。").show(0).delay(2000).hide(0);
    })
    // 输入金额
    $(".box .li .amount").on("input",function(e){
        var money=e.currentTarget.value;
        if (money == 0) {
            $(".box .li .reserveAmount").val("");
            $(".content .preview .btn").removeClass("red");
            return; 
        }
        $(".content .preview .btn").addClass("red");
        var reserveAmount = (Number(money) * (Number((($(".box .li .ratio").val()).split("%"))[0]) / 100)).toFixed(2);
        if (reserveAmount <= 500) {
            reserveAmount = 500;
        } else if (reserveAmount >= 100000) {
            reserveAmount = 100000;
        }
        $(".box .li .reserveAmount").val(reserveAmount);
    })
    // 比率选中
    $(".box .li .ratio").on("click",function(){
        $(this).blur();
        $(".template").show();
    })
    $(".template .cancel").on("click",function(){
        $(".template").hide();
    })
    $(".template .list>div").on("click",function(){
        var val=$(this).attr("data-value");
        $(".box .li .ratio").val(val);
        var reserveAmount = (Number($(".box .li .amount").val()) * (Number((($(".box .li .ratio").val()).split("%"))[0]) / 100)).toFixed(2);
        if (reserveAmount <= 500) {
            reserveAmount = 500;
        } else if (reserveAmount >= 100000) {
            reserveAmount = 100000;
        }
        $(".box .li .reserveAmount").val(reserveAmount);
        $(".template").hide();
    })
    // 下个月
    $(".calendarTem .years .right").on("click",function(){
        addMonth();
    })
    // 上个月
    $(".calendarTem .years .left").on("click",function(){
        LessMonth();
    })
    // 选择当前日
    $(".calendarTem .list").on("click",".optional",function(){
        var index2=$(this).attr("data-id"); //下标2
        var year=$(this).attr("data-year");
        var month=$(this).attr("data-month");
        index1=year.slice(2)+month; //下标1
        if($(this).hasClass("selected")){
            selectDate[index1][index2].status=false;
            $(this).removeClass("selected");
        }else{
            $(this).addClass("selected"); 
            selectDate[index1][index2].status=true;
        } 
    })
    // 隐藏日历蒙版
    $(".calendarTem .cancelOrbtn .cancel").on("click",function(){
        $(".calendarTem").hide();
    })
    // 计划按钮
    $(".content .preview ").on("click",".red",function(){
        $(".calendarTem").show();
    })

    // 确认提交   跳转计划详情
    $(".calendarTem .cancelOrbtn .btn").on("click",function(){
        putIn();
    })
})

/**
 * 获取信用卡列表
 */
function getList () {
    var data = {
      userName: baseFunction.encryption(loginName)
    };
    baseFunction.netRequest("quickCardBind", data, function (res) {
       //解密
      if (res.code == 200) {
        var data = JSON.parse(JSON.parse(res.data).cards);
        var html="";
        for (var i = 0; i < data.length; i++) {
            if(data[i].id==id){
                data[i].endNO = (data[i].cardno).slice(-4);
                cardno = data[i].cardno;// 当前还款银行卡号
                data[i].data = baseFunction.getData(data[i].billDate, data[i].rmentDate);
                for (var j = 0; j < bankCard.length; j++) {
                  if ((data[i].bankName).indexOf(bankCard[j].bankName) != -1) {
                    data[i].bg = "../static/img/" + bankCard[j].bankBackground + "@2x.png";
                    data[i].bg2 = "../static/img/" + bankCard[j].bigLogo + ".png";
                    var status=data[i].planStatus==1?"未还款":"还款中";
                    html="<img src='"+data[i].bg+"'>"
                    +"<div class='main'>"
                    +"<div class='top'>"
                    +"<img src='"+data[i].bg2+"'>"
                    +"<div class='name'>"
                    +"<text>"+data[i].bankName+" (<text>"+data[i].endNO+"</text>)</text>"
                    +"<text>"+data[i].trueName+"</text>"
                    +"</div>"
                    +"<text class='fr'>"+status+"</text>"
                    +"</div>"
                    +"<div class='bottom'>"
                    +"<div>"
                    +"<text>额度</text>"
                    +"<text>"+data[i].limitAmount+"</text>"
                    +"</div> "
                    +"<div class='fr'>"
                    +"<text>账单日期："+data[i].data.billingDay+"</text>"
                    +"<text>还款日期："+data[i].data.repaymentDate+"</text>"
                    +"</div>" 
                    +"</div></div>"
                  }
                }
                mainDate={
                    Bmonth: ((data[i].data.billingDay).split("月"))[0], //账单月
                    Bdate: (((data[i].data.billingDay).split("月"))[1]).split("日")[0],  //账单日
                    Rmonth: ((data[i].data.repaymentDate).split("月"))[0], //还款月
                    Rdate: (((data[i].data.repaymentDate).split("月"))[1]).split("日")[0], //还款日
                };
                $(".calendarTem .box .suggest").html("还款日期范围是"+data[i].data.billingDay+"至"+data[i].data.repaymentDate+"");
            }
          
        }
        $(".content .bankCard").html(html); 

      } else {
        $(".prompt").html(res.message).show(0).delay(1000).hide(0);
      }
      rendering();
    })
}

/**
 * 初始化日历控件
 * @param {*} currentDate  //当前日
 * @param {*} month //当前月
 * @param {*} year //当前年
 * @param {*} callback 回调
 */
function calendarInit (currentDate,month,year,callback){
    // 思绪
    // 1 得到每个月的天数 
    // 2 月初是周几 月末是周几
    // 3 从而判断在每个月天数 数组里面  往前后追加几天
    // 4 生成当月天数数组

    // 公共函数
    var getWeek = function (year,month,date) { //date  日
      var d = new Date();
      d.setYear(year);
      d.setMonth(month - 1);
      d.setDate(date);
      var weeks = [7, 1, 2, 3, 4, 5, 6];
      return weeks[d.getDay()];
    }
    // 1
    var dateArr=[]; //存放日子的数组
    var date = new Date();
    var year = year;  //当前年
    var month = month; //当前月
    var currentDate = currentDate; //当前日
    var daycount = (new Date(year, month, 0)).getDate(); //当月总共天数
    // 2
    var monthStartWeek = getWeek(year, month, 1);  //当月月初是周几
    var monthEndWeek = getWeek(year, month, daycount );  //当月月末是周几
    //console.log(monthStartWeek, monthEndWeek)
    //3
    if (monthStartWeek!=7){
      var preMOnthDayCount = (new Date(year, month - 1, 0)).getDate(); //上个月总共天数
      // 月初追加
      for (var i = 0; i < monthStartWeek; i++) {
        dateArr[i] = {
          value: preMOnthDayCount - monthStartWeek + (i + 1),
          status: false
        }
      }
    }
    // 添加本月
    var arr=[];
    for (var i = 0; i < daycount; i++) {
      arr[i] = {
        value: i + 1,
        status: false
      }
    }
    dateArr = dateArr.concat(arr);
    // 月末追加
    var currentDays = monthStartWeek + daycount;
    var yushu = currentDays%7;
    if(yushu!=0){ 
      var arr1=[];
      var zhuijia = 7 - yushu;
      for(var i=0;i<zhuijia;i++){
        arr1[i] = {
          value: i + 1,
          status: false
        }
      }
      dateArr = dateArr.concat(arr1);
    }
    // console.log(dateArr);
    // return dateArr;
    
    if(callback){
        callback(dateArr);
    }
}
/**
 * 初始化一下
 */
function rendering(){
    var date = new Date();
    var year = date.getFullYear();  //当前年
    var month = date.getMonth() + 1; //当前月
    var currentDate = date.getDate(); //当前日
    calendarInit (currentDate,month,year,function(data){
        baseDom(data);     
    })
}

/**
 * 下个月
 */
function addMonth(){
    year=month==12?year+1:year;
    month=month == 12 ?1: month+1;
    calendarInit (currentDate,month,year,function(data){
        baseDom(data);
            
    })
    //this.setArr();
}
/**
 * 上个月
 */
function LessMonth () {
    year= month == 1 ? year -1 : year;
    month=month == 1 ? 12 : month-1;
    calendarInit (currentDate,month,year,function(data){
        baseDom(data);
    })
    // this.setArr();
}
/**
 * 公共的dom操作
 * @param {*} data 
 */
function baseDom(data){
    var index = ((year) + "").slice(2) + month;
    if(!selectDate[index]){
        selectDate[index] = data;
    } 
    //dom操作
    var html="";
    selectDate[index].forEach(function(key,index){
        if(month>=mainDate.Bmonth && month<=mainDate.Rmonth){
            if(mainDate.Bdate<mainDate.Rdate){//还款日大于账单日
                if(key.value>=mainDate.Bdate && key.value<=mainDate.Rdate){
                    var status=key.status==true?"optional selected":"optional";
                    html+='<div data-id="'+index+'" data-year="'+year+'" data-month="'+month+'" class="'+status+'"> '+key.value+'</div>'
                }else{
                    html+='<div>'+key.value+'</div>';
                }
            }else{//账单日大于还款日
                if((key.value>=mainDate.Bdate && month==mainDate.Bmonth) || (key.value<=mainDate.Rdate && month==mainDate.Rmonth &&index<data.length-2)){
                    var status=key.status==true?"optional selected":"optional";
                    html+='<div data-id="'+index+'" data-year="'+year+'" data-month="'+month+'" class="'+status+'"> '+key.value+'</div>'
                }else{
                    html+='<div>'+key.value+'</div>';
                }
            }
        }else{
            html+='<div>'+key.value+'</div>'
        }
    })
    $(".calendarTem .list").html(html);
    $(".calendarTem .box .years>label").html(""+year+"年"+month+"月");
}


/**
 * 获取已选还款日期字符串
 */
function getTimeString(){
    var date=new Date();
    var beforYear = ((date.getFullYear()).toString()).slice(0,2);
    var timeTtring="";
    for(var i=0;i<selectDate.length;i++){
      if(selectDate[i]){
        for(var j=0;j<selectDate[i].length;j++){
          if (selectDate[i][j].status==true){
            var endYear=(i.toString()).slice(0,2);
            var month = (i.toString()).slice(2) < 10 ? "0" + (i.toString()).slice(2) : (i.toString()).slice(2);
            var value = selectDate[i][j].value < 10 ? "0" + selectDate[i][j].value : selectDate[i][j].value;
            timeTtring += beforYear + endYear + '-' + month + '-' + value+',';
          }
        }
      }
    }
    //console.log(timeTtring.slice(0, -1));
    return timeTtring.slice(0,-1);
}
/**
 * 确定提交
 */
function putIn(){
    $(".loding").show();
    $(".calendarTem").hide();
    var data={
      userName: baseFunction.encryption(loginName),
      cardno: baseFunction.encryption(cardno),
      rmentType:2,
      rmentDate: this.getTimeString(),
      planAmount: baseFunction.encryption($(".box .li .amount").val()),
      availAmt: baseFunction.encryption(($(".box .li .reserveAmount").val()).toString()),
      ruleCode: ruleCode,
    };
    baseFunction.netRequest("creditPlanMade",data,function(res){
        $(".loding").hide();
        
        $(".prompt").html(res.message).show(0).delay(2000).hide(0);
        if(res.code==200){
            setTimeout(function(){
                window.location.href='index_plannedOrder.html?data=' +encodeURIComponent(JSON.parse(res.data).plans) + '&loginName=' + loginName + '&accountBalance=' + accountBalance + '&aisle=' + aisle + ' &addRate=' + addRate + ' &rmentMode=' + rmentMode + ' &ruleCode=' + ruleCode +'&id='+id+''
            
            },1500)
        }
        // console.log(JSON.parse(JSON.parse(res.data).plans) );
    })
}